// 修正导入部分，移除不存在的FormItem
import React, { useState, useMemo, useCallback, useEffect } from 'react';
import {
  RadioGroup,
  Radio,
  TextArea,
  Button,
  Upload,
  Modal,
  Checkbox,
  // Form,
  Select,
  Col,
  Row,
  CardGroup,
  Avatar,
  Card,
} from '@douyinfe/semi-ui';

import { Image, Select as ArcoSelect, Form, Input, Message } from '@arco-design/web-react';
import deleteIcon from '@/assets/images/imageEdit/delete.svg';
import styles from './audioConfig.module.scss';
import { ICON_PATHS } from '@/assets/images/constants';
import MlsModal from '@/components/common/mlsModal';
import ScrollingText from '@/components/common/scrollingText';
import MlsUpload from '@/components/common/mlsUpload';
import MlsAudio from '@/components/common/mlsAudio';
import { timbreListGet, timbreGenerate } from '@/api/audio';
import { useLoading } from '@/components/common/mlsLoading/laodingText';
import sharedWebSocket from '@/services/sharedWebSocket.jsx';

const MENU_HEIGHTS = {
  pic: { area: '353px', textArea: '360px' },
  multi: { area: '134px', textArea: '224px' },
  image: { area: '227px' },
  default: { area: '', textArea: '' },
};
const MOOL_LIST = ['开心', '自然', '生气', '惊讶', '悲伤', '厌烦', '害怕'];
const DEFAULT_DELICACY = [
  { label: '笑声', url: ICON_PATHS.LAUGHTER_ICON },
  { label: '咳嗽', url: ICON_PATHS.COUGH_ICON },
  { label: '停顿', url: ICON_PATHS.STANDSTILL_ICON },
];
const FILTER_TYPE = [
  {
    label: '全部',
    value: '全部',
  },
  {
    label: '男声',
    value: '男声',
  },
  {
    label: '女声',
    value: '女声',
  },
  {
    label: '男童',
    value: '男童',
  },
  {
    label: '女童',
    value: '女童',
  },
  {
    label: '其他',
    value: '其他',
  },
];
// 添加示例数据，确保有长文本可以测试轮播效果
const soundNames = [
  '成熟稳重',
  '清脆甜美-女声',
  '活泼可爱-女童-超长名称示例活泼可', // 这个应该会触发轮播
  '阳光开朗-男童',
  '低沉沙哑-男声-非常长的名字', // 这个应该会触发轮播
  '温柔婉约-女声',
];
const SAMPLING_RATE = [
  {
    label: '48KHZ',
    value: '48KHZ',
  },
  {
    label: '44.1KHZ',
    value: '44.1KHZ',
  },
  {
    label: '24KHZ',
    value: '24KHZ',
  },
  {
    label: '22.05KHZ',
    value: '22.05KHZ',
  },
  {
    label: '16KHZ',
    value: '16KHZ',
  },
];
export default function MainEdit({ currentMenuKey }) {
  // 获取高度配置
  const heights = MENU_HEIGHTS[currentMenuKey] || MENU_HEIGHTS.default;
  const [demandType, setDemandType] = useState(1); // 指令生成 1  参考音频生成  2
  const [voiceType, setVoiceType] = useState(null);
  const [voiceModalVisible, setVoiceModalVisible] = useState(false);
  const [filterType, setFilterType] = useState('全部');
  const [selectedCardIndex, setSelectedCardIndex] = useState(-1);

  const [uploadAudioList, setUploadAudioList] = useState([]);
  const [referencePrompt, setReferencePrompt] = useState('');
  const [controlText, setControlText] = useState('');
  const [audioName, setAudioName] = useState('');
  const [samplingRate, setSamplingRate] = useState('48KHZ');
  const [selectedTimbre, setSelectedTimbre] = useState({});
  const [timbreType, setTimbreType] = useState(1); // 音色类型 1 预设音色 2 自定义音色
  const { showLoading, hideLoading } = useLoading();
  const [voiceList, setVoiceList] = useState([]);
  const [disabledField, setDisabledField] = useState(false);

  const changeControlText = useCallback(
    value => {
      setControlText(value);
    },
    [setControlText]
  );

  const changePrompt = useCallback(
    value => {
      setReferencePrompt(value);
    },
    [setReferencePrompt]
  );

  const clearReferencePrompt = useCallback(() => {
    setReferencePrompt('');
  }, [setReferencePrompt]);

  // 创建ref用于获取TextArea的DOM元素
  const textAreaRef = React.useRef(null);
  const moolTextAreaRef = React.useRef(null);

  // 渲染参考提示词区域
  const renderReferencePromptSection = useCallback(
    (placeholder = '请输入您的台词内容...') => (
      <>
        <div className={styles.titleSection}>台词内容</div>
        <div className={styles.area} style={{ maxHeight: 400 }}>
          <TextArea
            id="reference-prompt"
            ref={textAreaRef}
            value={referencePrompt}
            onChange={changePrompt}
            placeholder={placeholder}
            maxCount={400}
            className={styles.linesTextArea}
          />

          <div className={styles.opts}>
            <Image
              className={styles.img}
              src={deleteIcon}
              preview={false}
              draggable={false}
              onClick={clearReferencePrompt}
            />
          </div>
        </div>
      </>
    ),
    [referencePrompt, changePrompt, clearReferencePrompt]
  );

  const handleDemandTypeChange = useCallback(
    e => {
      const newValue = e.target.value || 1;
      setDemandType(newValue);
      setSelectedCardIndex(-1);
      setUploadAudioList([]);
      if (newValue === 1) {
        setSelectedTimbre({});
      } else {
        setReferencePrompt(referencePrompt.replace(/@(笑声|咳嗽|停顿)/g, ''));
        setDisabledField(false);
        setSamplingRate('48KHZ');
      }
    },
    [referencePrompt]
  );

  const handleSelctVoice = useCallback(e => {
    setVoiceModalVisible(true);
  }, []);

  // 添加筛选类型变更处理函数
  const handleFilterTypeChange = useCallback(value => {
    setFilterType(value);
    console.log('filterType', value);
  }, []);
  // 添加卡片选中处理函数
  const handleCardSelect = useCallback(index => {
    setSelectedCardIndex(index);
  }, []);

  const getList = useCallback(
    ({ filterType, isCustom = false }) => {
      let obj = {
        cate: filterType === '全部' ? '' : filterType,
        isCustom,
        pageNum: 1,
        pageSize: 100000,
      };
      timbreListGet(obj)
        .then(res => {
          if (res.code === 200) {
            setVoiceList(res.data.timbreList || []);
          }
        })
        .finally(() => {
          hideLoading();
        });
    },
    [hideLoading, filterType, setVoiceList]
  );

  // 添加：页面加载时自动查询数据
  // 新增的useEffect - 专门处理弹窗打开时的数据加载
  useEffect(() => {
    if (voiceModalVisible) {
      showLoading('加载中...');
      // 弹窗打开时，使用当前选中的timbreType和filterType来加载数据
      const isCustom = timbreType === 2;
      getList({ filterType, isCustom });
    }
  }, [voiceModalVisible, timbreType, filterType, getList, showLoading]);

  // 音色类型变更处理函数
  const handleTimbreTypeChange = useCallback(
    e => {
      console.log('timbreType', e.target.value);

      const newValue = e.target.value || 1;
      setTimbreType(newValue);
      setSelectedCardIndex(-1);
    },
    [setSelectedCardIndex, setTimbreType]
  );

  const renderVoiceMadalContent = useCallback(() => {
    return (
      <div className={styles.voiceModalContent}>
        <div className={styles.topToolColumn}>
          <div className={styles.typeTab}>
            <RadioGroup
              type="button"
              buttonSize="small"
              className={styles.typeGroup}
              value={timbreType}
              onChange={handleTimbreTypeChange}>
              <Radio value={1}>
                <div className={styles.typeItem}>预设音色</div>
              </Radio>
              <Radio value={2}>
                <div className={styles.typeItem}>自定义</div>
              </Radio>
            </RadioGroup>
          </div>
          <div className={styles.filterBox}>
            <span>筛选</span>

            {FILTER_TYPE.map(item => (
              <Button
                className={`${styles.filterBtn} ${
                  filterType === item.value ? styles.filterBtnActive : ''
                }`}
                key={item.value}
                onClick={() => handleFilterTypeChange(item.value)}>
                {item.label}
              </Button>
            ))}
          </div>
        </div>
        <div className={styles.soundListBox}>
          <CardGroup spacing={14}>
            {voiceList.map((item, index) => (
              <Card
                className={`${styles.soundCardItem} ${
                  selectedCardIndex === index ? styles.cardSelected : ''
                }`}
                key={index}
                shadows="hover"
                onClick={() => handleCardSelect(index)}>
                <Avatar src={item.imgUrl} className={styles.soundAvatar} />
                {/* <span className={styles.soundName}>成熟稳重高冷深邃-男声</span> */}
                {/* <div
                className={styles.soundNameContainer}
                ref={el => (textContainerRefs.current[index] = el)}
                data-overflow={textOverflowStates[index] ? 'true' : 'false'}>
                <span className={styles.soundNameText}>{item.name}</span>
              </div> */}
                <ScrollingText
                  text={item.name}
                  width={90}
                  height={22}
                  speed={4}
                  gapDistance={10}
                  // className={styles.soundNameContainer}
                />
                {/* <Image
                  className={styles.moreIcon}
                  width={20}
                  src={ICON_PATHS.SOUND_DELETE_ICON}
                  draggable={false}
                  preview={false}
                  onClick={() => handleDelete(index)}
                /> */}
              </Card>
            ))}
          </CardGroup>
        </div>
        {selectedCardIndex !== -1 && (
          <div className={styles.audioPlayer}>
            <MlsAudio showELseControl={false} showVolumeControl={false}></MlsAudio>
          </div>
        )}
      </div>
    );
  }, [filterType, selectedCardIndex, timbreType, voiceList]);

  const audioUploadSuccess = useCallback(
    (result, file) => {
      let obj = {
        name: file.name,
        url: result.url,
      };
      setUploadAudioList([obj]);
    },
    [setUploadAudioList]
  );

  const addMoolText = useCallback(
    text => {
      // 获取TextArea的DOM元素
      const textAreaElement = moolTextAreaRef.current;
      if (textAreaElement) {
        // 获取当前光标位置
        const start = textAreaElement.selectionStart;
        const end = textAreaElement.selectionEnd;

        // 在光标位置插入新内容
        const newText = controlText.slice(0, start) + ` @${text}` + controlText.slice(end);
        setControlText(newText);

        // 在下一次渲染后恢复光标位置
        setTimeout(() => {
          if (textAreaElement) {
            // 计算新的光标位置
            const newCursorPosition = start + text.length + 2; // +2 是因为添加了 @ 和一个空格
            textAreaElement.selectionStart = newCursorPosition;
            textAreaElement.selectionEnd = newCursorPosition;
            textAreaElement.focus(); // 保持焦点在文本域
          }
        }, 0);
      } else {
        // 如果无法获取光标位置，就回退到原始的追加方法
        setControlText(`${controlText} @${text}`);
      }
    },
    [controlText, setControlText]
  );
  // 在光标位置插入文本的函数
  const addDelicacyText = useCallback(
    text => {
      // 获取TextArea的DOM元素
      const textAreaElement = textAreaRef.current;
      if (textAreaElement) {
        // 获取当前光标位置
        const start = textAreaElement.selectionStart;
        const end = textAreaElement.selectionEnd;

        // 在光标位置插入新内容
        const newText = referencePrompt.slice(0, start) + ` @${text}` + referencePrompt.slice(end);
        setReferencePrompt(newText);

        // 在下一次渲染后恢复光标位置
        setTimeout(() => {
          if (textAreaElement) {
            // 计算新的光标位置
            const newCursorPosition = start + text.length + 2; // +2 是因为添加了 @ 和一个空格
            textAreaElement.selectionStart = newCursorPosition;
            textAreaElement.selectionEnd = newCursorPosition;
            textAreaElement.focus(); // 保持焦点在文本域
          }
        }, 0);
      } else {
        // 如果无法获取光标位置，就回退到原始的追加方法
        setReferencePrompt(`${referencePrompt} @${text}`);
      }
    },
    [referencePrompt, setReferencePrompt]
  );

  const changeDisabledStatus = useCallback(
    disabled => {
      setDisabledField(disabled);
      if (disabled) {
        setControlText('');
        // setSamplingRate(undefined);
        // 去掉台词referencePrompt 中的 @笑声、@咳嗽、@停顿标记
        setReferencePrompt(referencePrompt.replace(/@(笑声|咳嗽|停顿)/g, ''));
      }
    },
    [setDisabledField, setControlText, setReferencePrompt, referencePrompt]
  );

  const confirmSelectedVoice = useCallback(() => {
    console.log('voiceList[selectedCardIndex]', voiceList[selectedCardIndex]);

    if (selectedCardIndex !== -1) {
      // 如果是自定义音色,需要禁用提示词 标签 采样率
      const timbreObj = voiceList[selectedCardIndex];
      if (timbreObj.isCustom) {
        changeDisabledStatus(true);
      } else {
        changeDisabledStatus(false);
      }
      setSelectedTimbre(voiceList[selectedCardIndex]);
      setVoiceModalVisible(false);
      setVoiceList([]);
      setSelectedCardIndex(-1);
      setTimbreType(1);
      setFilterType(FILTER_TYPE[0].value);
    }
  }, [
    selectedCardIndex,
    setSelectedTimbre,
    setVoiceModalVisible,
    voiceList,
    setFilterType,
    setTimbreType,
    changeDisabledStatus,
  ]);

  const cancelSelectVoice = useCallback(() => {
    setSelectedCardIndex(-1);
    setVoiceModalVisible(false);
    setTimbreType(1);
    setFilterType(FILTER_TYPE[0].value);
    // setSelectedTimbre({});
  }, [setSelectedCardIndex, setVoiceModalVisible, setTimbreType, setFilterType]);

  const handleGenerateVoice = useCallback(() => {
    console.log('selectedTimbre', selectedTimbre);
    if (referencePrompt.trim().length === 0) {
      Message.error('请输入台词');
      return;
    }
    if (audioName.trim().length === 0) {
      Message.error('请输入音频名称');
      return;
    }

    // 根据demandType 来判断是指令生成command还是参考音频生成 voice
    const generateType = demandType === 1 ? 'command' : 'voice';
    // 根据不同的类型判断提示用户输入
    if (demandType === 1) {
      if(!selectedTimbre?.id) {
        Message.error('请选择音色');
        return;
      }
      
    } else {
      if (!uploadAudioList?.length) {
        Message.error('请上传参考音频');
        return;
      }
    }
    if (!samplingRate) {
      Message.error('请选择采样率');
      return;
    }

    // 如果是指令生成, 根据选择的音色, selectedTimbre.isCustom 来判断 prompt, samplingRate是否需要
    const obj =
      demandType === 1
        ? {
            generateType,
            text: referencePrompt,
            prompt: controlText || null,
            audioName: audioName,
            timbreId: selectedTimbre?.id,
            timbre: selectedTimbre?.name,
            samplingRate: samplingRate,
          }
        : {
            generateType,
            text: referencePrompt,
            audioName: audioName,
            referenceAudioUrl: uploadAudioList[0]?.url,
            samplingRate: samplingRate,
          };
    showLoading('合成中...');
    timbreGenerate(obj)
      .then(res => {
        if (res.code === 200) {
        } else {
          Message.error(res.msg || '合成失败');
          hideLoading();
        }
      })
      .catch(() => {
        Message.error('合成失败');
        hideLoading();
      });
  }, [
    controlText,
    selectedTimbre,
    samplingRate,
    demandType,
    audioName,
    showLoading,
    hideLoading,
    timbreGenerate,
    uploadAudioList,
    referencePrompt,
  ]);

  return (
    <div className={styles.mainEdit}>
      <div className={styles.top}>
        <div className={styles.header}>
          <div className={styles.title}>控制语音合成</div>
        </div>
        {renderReferencePromptSection()}

        <div className={styles.delicacyBox}>
          <span style={{ margin: '0 6px' }}>细腻度: </span>
          {DEFAULT_DELICACY.map(item => (
            <Button
              size="small"
              className={`${styles.btn} ${styles.delicacyBtn}`}
              key={item.label}
              disabled={disabledField || demandType === 2}
              onClick={() => addDelicacyText(item.label)}>
              <Image
                className={styles.delicacyIcon}
                src={item.url}
                draggable={false}
                preview={false}
              />
              {item.label}
            </Button>
          ))}
        </div>
        <div className={styles.middle}>
          <RadioGroup
            type="button"
            buttonSize="small"
            className={styles.typeGroup}
            value={demandType}
            onChange={handleDemandTypeChange}>
            <Radio value={1}>
              <div className={styles.typeItem}>指令生成</div>
            </Radio>
            <Radio value={2}>
              <div className={styles.typeItem}>参考音频</div>
            </Radio>
          </RadioGroup>
        </div>
        <div className={styles.area} style={{ maxHeight: 400 }}>
          {demandType === 1 && (
            <TextArea
              id="moolTextArea"
              ref={moolTextAreaRef}
              value={controlText}
              disabled={disabledField}
              onChange={changeControlText}
              style={{ maxHeight: 340 }}
              placeholder={'请输入想要生成情绪或语音等指令...'}
              maxCount={400}
            />
          )}
          {demandType === 2 && (
            <>
              <MlsUpload
                className={styles.uploadBox}
                accept="audio/*"
                onSuccess={audioUploadSuccess}
                children={() => (
                  <div className={styles.uploadBtn}>
                    <Image
                      className={styles.uploadIcon}
                      src={ICON_PATHS.ADD_UPLOAD_ICON}
                      preview={false}
                      draggable={false}
                    />
                    <span>
                      <i style={{ fontStyle: 'normal', color: 'rgba(255,255,255,.5)' }}>上传</i>
                      「参考音频」
                    </span>
                  </div>
                )}
              />
              {uploadAudioList.length > 0 && (
                <div className={styles.uploadAudioBox}>
                  <div className={styles.item}>
                    <MlsAudio
                      src={uploadAudioList[0].url}
                      showTitle={false}
                      showELseControl={true}
                      showVolumeControl={false}
                      onOtherAction={(action, url) => {
                        if (action === 'delete') {
                          setUploadAudioList(uploadAudioList.filter(item => item.url !== url));
                        }
                      }}
                    />
                  </div>
                </div>
              )}
            </>
          )}
        </div>
        {demandType === 1 && (
          <div className={styles.moolBox}>
            <span style={{ margin: '0 6px' }}>语气: </span>
            {MOOL_LIST.map(item => (
              <Button
                size="small"
                className={`${styles.btn}`}
                key={item}
                disabled={disabledField}
                onClick={() => addMoolText(item)}>
                {item}
              </Button>
            ))}
          </div>
        )}
      </div>
      {
        <div className={`${styles.bottom} ${demandType !== 1 ? styles.configAudio : ''}`}>
          <div className={styles.selectSection}>
            <div className={styles.configItem}>
              <span className={styles.configItemTitle}>音频名称</span>
              <Input
                placeholder="请输入音频名称..."
                className={styles.select}
                value={audioName}
                onChange={setAudioName}
              />
            </div>
            {demandType === 1 && (
              <div className={styles.configItem}>
                <span className={styles.configItemTitle}>音色选择</span>
                <Button
                  className={`${styles.select} ${styles.voiceBtnSelect}`}
                  onClick={handleSelctVoice}>
                  {selectedTimbre.id ? (
                    <span title={selectedTimbre.name} className={styles.voiceBtnSelectText}>
                      {selectedTimbre.name}
                    </span>
                  ) : (
                    <span
                      className={styles.voiceBtnSelectText}
                      style={{ color: 'rgba(255, 255, 255, 0.5)' }}>
                      请选择
                    </span>
                  )}
                  <Image
                    className={styles.voiceBtnSelectIcon}
                    src={ICON_PATHS.RETREAT_ICON}
                    draggable={false}
                    preview={false}
                  />
                </Button>
              </div>
            )}
            <div className={styles.configItem}>
              <span className={styles.configItemTitle}>采样率</span>

              <ArcoSelect
                className={styles.select}
                value={samplingRate}
                // disabled={disabledField}
                onChange={setSamplingRate}>
                {SAMPLING_RATE.map(item => (
                  <ArcoSelect.Option key={item.value} value={item.value}>
                    {item.label}
                  </ArcoSelect.Option>
                ))}
              </ArcoSelect>
            </div>
          </div>
          <Button className="button buttonPrimary" onClick={handleGenerateVoice}>
            合成
          </Button>
        </div>
      }
      <MlsModal
        title="选择音色"
        visible={voiceModalVisible}
        onConfirm={confirmSelectedVoice}
        onCancel={cancelSelectVoice}
        modalProps={{
          width: 1120,
          className: `custom-semi-modal-style`,
          nofooter: false,
          maskClosable: false,
        }}
        // footerContent={<span></span>}
        children={renderVoiceMadalContent()}
      />
    </div>
  );
}
